<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>导航二级菜单</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    main {
      width: 500px;
      margin: 0 auto;
    }

    ul {
      list-style: none;
    }

    .menu {
      display: block;
      width: 100px;
      height: 50px;
      font-size: 20px;
      background-color: orange;
      text-align: center;
      line-height: 50px;
      cursor: pointer;
    }

    .activate {
      background-color: red;
    }

    .main-item {
      float: left;
    }

    .menu-ul {
      display: none;
    }

    .item {
      width: 100px;
      height: 50px;
      background-color: orange;
      text-align: center;
      line-height: 50px;
      border-top: 1px solid purple;
      cursor: pointer;

    }

    .on {
      display: block;
    }
  </style>
</head>

<body>
  <main>
    <ul class="main">
      <li class="main-item">
        <span class="menu ">一</span>
        <ul class="menu-ul ">
          <li class="item">1</li>
          <li class="item">2</li>
          <li class="item">3</li>
          <li class="item">4</li>
        </ul>
      </li>
      <li class="main-item">
        <span class="menu">二</span>
      </li>
      <li class="main-item">
        <span class="menu">三</span>
        <ul class="menu-ul">
          <li class="item">1</li>
          <li class="item">2</li>
          <li class="item">3</li>
          <li class="item">4</li>
        </ul>
      </li>
      <li class="main-item">
        <span class="menu">四</span>
        <ul class="menu-ul">
          <li class="item">1</li>
          <li class="item">2</li>
          <li class="item">3</li>
          <li class="item">4</li>
        </ul>
      </li>
      <li class="main-item">
        <span class="menu">五</span>
      </li>
    </ul>
  </main>

  <script>
    // 获取所有菜单栏元素
    let mainItems = document.querySelectorAll(".main-item");
    let menus = document.querySelectorAll(".menu")
    // 批量注册移入事件
    mainItems.forEach(function (mainItem, index) {
      mainItem.addEventListener("mouseenter", function () {
        menus[index].classList.add("activate")
        this.children[1] && this.children[1].classList.add("on")
      })
      // 注册移出事件
      mainItem.addEventListener("mouseleave", function () {
        menus[index].classList.remove("activate")
        this.children[1] && this.children[1].classList.remove("on")
      })
    })
  </script>
</body>

</html>